package com.oazon.sonos.util;


import java.io.InputStream;  
import java.util.ArrayList;  
import java.util.List;  

import javax.xml.parsers.SAXParser;  
import javax.xml.parsers.SAXParserFactory;  

import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;  
  
  
public class MediaUriParse implements IParse{  
	private static MediaUriParse PARSE;
	
	
	public static MediaUriParse getInstance() {
		if (PARSE == null) {
			PARSE = new MediaUriParse();
		}
		return PARSE;
	}
      

	
    public Object parse(InputStream is) throws Exception {  
        SAXParserFactory factory = SAXParserFactory.newInstance();  //取得SAXParserFactory实例  
        SAXParser parser = factory.newSAXParser();                  //从factory获取SAXParser实例  
        MyHandler handler = new MyHandler();                        //实例化自定义Handler  
        parser.parse(is, handler);                                  //根据自定义Handler规则解析输入流  
        List<String> result = handler.getMediaUris();  
        if (result != null && result.size() > 0) {
        	return result.get(0);
        }
        return null;
    }  
      
    //需要重写DefaultHandler的方法  
    private class MyHandler extends DefaultHandler {  
        private List<String> mediaUris;
        private String mediaUri = "";  
        private StringBuilder builder;  
          
        //返回解析后得到的Book对象集合  
        public List<String> getMediaUris() {  
            return mediaUris;  
        }  
          
        @Override  
        public void startDocument() throws SAXException {  
            super.startDocument();  
            mediaUris = new ArrayList<String>();
            builder = new StringBuilder();  
        }  
  
        @Override  
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {  
            super.startElement(uri, localName, qName, attributes);  
            if (localName.equals("getMediaURIResponse")) {  
            	mediaUri = "";
            }  
            builder.setLength(0);   //将字符长度设置为0 以便重新开始读取元素内的字符节点  
        }  
          
        @Override  
        public void characters(char[] ch, int start, int length) throws SAXException {  
            super.characters(ch, start, length);  
            builder.append(ch, start, length);  //将读取的字符数组追加到builder中  
        }  
          
        @Override  
        public void endElement(String uri, String localName, String qName) throws SAXException {  
            super.endElement(uri, localName, qName);  
            if (localName.equals("getMediaURIResult")) {  
            	mediaUri = builder.toString();  
            } else if (localName.equals("getMediaURIResponse")) {
            	mediaUris.add(mediaUri);
            }
        }  
    }
}  